package com.dark.sys.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dark.common.repository.hibernate.HibernateDao;
import com.dark.common.utils.BeanUtils;
import com.dark.sys.entity.Auth;
import com.dark.sys.service.AuthService;
import com.dark.sys.web.dto.AuthDto;


@Service
public class AuthServiceImpl implements AuthService {
	
	@Autowired
	private HibernateDao<Auth, Integer> basedaoAuth ;
	
	@Override
	public void allotUserRole(AuthDto dto) {
		String userIds = dto.getUserIds() ;
		if(null != userIds && !"".equals(userIds)) {
			String[] split = userIds.split(",") ;
			for (String userId : split) {
				Auth entity = new Auth() ;
				BeanUtils.copyNotNullProperties(dto, entity);
				entity.setUserId(Integer.parseInt(userId)) ;
				
				//先删除原有的角色资源权限
				deleteByUserId(Integer.parseInt(userId));
				
				if(null != dto.getRoleIds() && !"".equals(dto.getRoleIds().trim())) {
					this.basedaoAuth.save(entity) ;
				}
			}
		}
	}
	private void deleteByUserId(Integer roleId) {
		this.basedaoAuth.executeSQL("delete from sys_auth where userId=?", new Object[]{roleId}) ;
	}

	@Override
	public AuthDto get(AuthDto dto) {
		StringBuffer queryString = new StringBuffer("SELECT t.* FROM sys_auth t WHERE 1=1") ;
		
		Map<String, Object> alias = new HashMap<String, Object>() ;
		queryString = addWhere(queryString, alias, dto) ;
		
		return (AuthDto) this.basedaoAuth.findUniqueSQL(queryString.toString(), alias, AuthDto.class, false) ;
	}
	
	
	private StringBuffer addWhere(StringBuffer queryString, Map<String, Object> alias, AuthDto dto) {
		if(null != dto) {
			if(null != dto.getId()) {
				queryString.append(" AND t.id=:id") ;
				alias.put("id", dto.getId()) ;
			}
			if(null != dto.getUserId()) {
				queryString.append(" AND t.userId=:userId") ;
				alias.put("userId", dto.getUserId()) ;
			}
			if(null != dto.getGroupId()) {
				queryString.append(" AND t.groupId=:groupId") ;
				alias.put("groupId", dto.getGroupId()) ;
			}
			if(null != dto.getJobId()) {
				queryString.append(" AND t.jobId=:jobId") ;
				alias.put("jobId", dto.getJobId()) ;
			}
			
		}
		return queryString;
	}
	@Override
	public AuthDto getByUserId(Integer userId) {
		String queryString = "SELECT t.* FROM sys_auth t WHERE t.userId=?" ;
		return (AuthDto) this.basedaoAuth.findUniqueSQL(queryString, new Object[]{userId}, AuthDto.class, false) ;
	}
}
